package com.ttbj.payment.original.wxpay.utils;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * Http请求（这里用户获取订单url生成的二维码）
 *
 */
public class HttpUtil {
	
	private final static int CONNECT_TIMEOUT = 5000;
	private final static String DEFAULT_ENCODING = "UTF-8";
	
	
	public static String postData(String urlStr, String data) {
		return postData(urlStr, data, null);
	}
	
	public static String postData(String urlStr, String data, String contentType) {
		BufferedReader reader = null;
		try {
			URL url = new URL(urlStr);
			URLConnection connection = url.openConnection();
			//默认为false 发送post请求必须设置setDoOutput(true)
			connection.setDoOutput(true);
			//设置请求超时时间
			connection.setConnectTimeout(CONNECT_TIMEOUT);
			connection.setReadTimeout(CONNECT_TIMEOUT);
			if (contentType != null && !"".equals(contentType)) {
				connection.setRequestProperty("content-type", contentType);
			}
			OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), DEFAULT_ENCODING);
			if (data == null) {
				data = "";
			}
			writer.write(data);
			writer.flush();
			writer.close();
			
			reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), DEFAULT_ENCODING));
			StringBuilder sBuilder = new StringBuilder();
			String line = null;
			while((line = reader.readLine())!=null) {
				sBuilder.append(line);
				sBuilder.append("\r\n");
			}
			return sBuilder.toString();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				if (reader != null) {
					reader.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}
}
